package cn.yogehaoren.quickstart;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author WangNing
 * @since 1.0
 */
public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1. 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("k8s-node2");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        //2. 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();

        // 3. 通过Connection创建Channel
        Channel channel = connection.createChannel();

        // 4. 声明一个队列
        String queueName = "test001";
        // 参数1: 队列名
        // 参数2: 是否开启持久化(即同步到磁盘)
        // 参数3: 是否独占(开启后, 该队列只允许用于本连接)
        // 参数4: 是否自动删除(当队列不再使用时，集群自动删除该队列)
        // 参数5: 可选参数
        channel.queueDeclare(queueName, true, false, false, null);

        // 5. 创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

        // 6. 设置channel
        channel.basicConsume(queueName, true, queueingConsumer);

        // 7. 获取消息
        while (true){

            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("消费端: "+msg);

        }


    }

}
